#coding: utf-8
from django.shortcuts import render_to_response
from models import Template
from savetogdata import saveTemplateToGoogle

from google.appengine.api import users
#import sys
#reload(sys)
#sys.setdefaultencoding('utf-8')

def index(request):
    user = users.GetCurrentUser()
    if not user:
        greeting = ("<a href=\"%s\">需要登录Google帐号，点击进行登录</a>." % 
                    users.create_login_url("/"))
        return render_to_response('msg.html', {'msg':greeting, 'url':'/'})
    

    email_reply_to = request.POST.get('reply_to', '') 
    isSendMyself = request.POST.get('chkSendmyself', False) #是否发送给自己
    ToMail = request.POST.get('txtSendList', None)#.decode("").encode("UTF-8")
    Macro = request.POST.get('txtMacroList', None)#.decode("UTF-8")
    Title = request.POST.get('txtMailSubject', None)#.encode("UTF-8")
    MailContext = request.POST.get('fck_mail_body', None)#.encode("UTF-8")
    tempName = request.POST.get('tempName', None)#.encode("UTF-8")
    gLogMail = request.POST.get('gLogMail', None) #gg邮箱
#    gPsw = request.POST.get('gPsw', '')
    gfileName = request.POST.get('gSheetName', '').strip()
    wksht_name = request.POST.get('wksht_name', '').strip()
    
#    code = sys.getdefaultencoding()
    
    action = request.GET.get('action', '')
    if action == 'locad':
        temp = Template(#user_email = user.email(), 
                        owner = user,
                        temp_name = tempName.decode("utf-8"),
                        reply_tomail = email_reply_to.decode("utf-8"), 
                        send_myself = isSendMyself,
                        mail_list = ToMail.decode("utf-8"), 
                        marco = Macro.decode("utf-8"), 
                        title = Title.decode("utf-8"), 
                        mail_context = MailContext.decode("utf-8"), 
                        glogin_mail = gLogMail.decode("utf-8"), 
                        gfile_name = gfileName.decode("utf-8"), 
                        gwksht_name = wksht_name.decode("utf-8"))
        
        temp.save()
        return render_to_response('msg.html', {'msg': u'模版保存成功！', 'url':'/'})
        #else:
        #    return render_to_response('msg.html', {'msg': u'模版保存失败！', 'url':'/'})

    elif action == 'google':
        rt = saveTemplateToGoogle(gLogMail, gPsw, gfileName, wksht_name, tempName,\
                             server, user, Email_Sender, isSendMyself, \
                             ToMail, Macro, Title, MailContext)
        if rt:
             return render_to_response('msg.html', {'msg': u'模版保存成功,在google上創建了文件: %s' % tempName, 'url':'/email/'})
        else:
             return render_to_response('msg.html', {'msg': u'模版保存失败', 'url':'/email/'})
        pass
    else:
        return render_to_response('msg.html', {'msg': '参数差误，非法链接', 'url':'/email/'})
#end index()

if __name__ == '__main__':
    pass
